﻿using System;
using System.Collections.Generic;

namespace HCore
{
    public static class CommandFactory
    {
        public delegate Command CommandCreator(InputMemoryBitStream input);

        private static Dictionary<byte, CommandCreator> _creators = new Dictionary<byte, CommandCreator>();

        public static void SetDisplayCreator(byte commandType, Type type)
        {
            Debug.Assert(!_creators.ContainsKey(commandType));
            _creators[commandType] = input =>
            {
                Command command = (Command) Activator.CreateInstance(type);
                command.Read(input);
                return command;
            };
        }

        public static Command ReadAndCreate(InputMemoryBitStream input)
        {
            int oldBitHeap = input.GetBitHead();
            byte commandType = input.ReadByte();
            input.SetBitHead(oldBitHeap);

            Debug.Assert(_creators.ContainsKey(commandType));

            return _creators[commandType].Invoke(input);
        }
    }
}